$(function () {
    initDatagrid();
    // 初始化商品分类列表
    $.util.get($.util.getRequestJson('/dict/findByGroupKey.json'),{groupKey:"commtityType"},function(data){
        $('#commtityType').combobox({
            valueField:'dictKey',
            textField:'dictText',
            data:data.rows
        });
    });
    // 带参数的数据请求
    $("#queryButton").click(function(){
        var commtityType = $("#commtityType").combobox('getValue');
        var verifyStatus = $("#verifyStatus").combobox('getValue');
        if(commtityType == '请选择商品分类'){
            commtityType = null;
        }
        $("#listTable").datagrid('load',{
            verifyStatus:verifyStatus,
            queryStr:$("#queryStr").val(),
            Categories:commtityType,
        })
    })
});

// 表格内容初始化
function initDatagrid() {
    var url = $.util.getRequestJson('/json/productManage.productVerifyList.json');
    $('#listTable').datagrid({
        // type=0 即查询 普通公告类型数据
        url: url ,
        idField:'id',
        fit: true,
        pagination: true,
        pageSize: 30,
        checkOnSelect: false,
        selectOnCheck: false,
        singleSelect: true,
        toolbar: '#toolbarButton',
        fitColumns: true,
        columns: [
            [
                {
                    field:"ck",
                    checkbox:"true"
                },
                /*{
                    field: 'id',
                    title: '商品编号',
                    align: 'center',
                    width:20
                },*/
                {
                    field: 'title',
                    title: '商品名称',
                    width:22
                },
                {
                    field: 'name',
                    title: '发布商户',
                    width:20,
                    formatter: function (value, row) {
                        return value == null ? "——" : value;
                    }
                },
                /*{
                    field: 'dictText',
                    title: '商品分类',
                    align: 'center',
                    width:25
                },*/
                {
                    field: 'needScore',
                    title: '兑换要求积分',
                    align: 'center',
                    width:10
                },
                {
                    field: 'createTime',
                    title: '创建时间',
                    align: 'center',
                    width:20
                },
                {
                    field: 'isHome',
                    title: '首页推荐',
                    align: 'center',
                    width:12,
                    formatter:function(value){
                        if(value == '0'){
                            return "不推荐"
                        }else if(value == '1'){
                            return "推荐"
                        }else{
                            return "--"
                        }
                    }
                },
                {
                    field: 'isQuality',
                    title: '精品专区',
                    align: 'center',
                    width:12,
                    formatter:function(value){
                        if(value == '0'){
                            return "否"
                        }else if(value == '1'){
                            return "是"
                        }else{
                            return "--"
                        }
                    }
                },
                {
                    field: 'verifyResult',
                    title: '审核状态',
                    align: 'center',
                    width:15,
                    formatter:function(value,row){
                        if(value == '0'){
                            return "<font color='red'>未通过</font>"
                        }else if(value == '1'){
                            return "<font color='green'>已通过</font>"
                        }else{
                            return "待审核"
                        }
                    }
                },
                {
                    field: 'context',
                    width:20,
                    align: 'center',
                    title: '操作',
                    formatter: function (value, row) {
                        var aEl = '<a href=javascript:findDetail("{0}"); class="easyui-tooltip" title="详情">详情</a>' +
                            ' | <a href=javascript:deleteProduct("{0}"); class="easyui-tooltip" title="删除">删除</a>' +
                            ' | <a href=javascript:verifyProduct("{0}"); class="easyui-tooltip" title="审核">审核</a>';
                        //格式化操作按钮
                        return $.string.format(aEl,row.id);
                    }
                }
            ]
        ]
    });
}

// 批量审核
function batchVerify(){
    var selections = $("#listTable").datagrid('getChecked');
    if(selections.length == 0){
        $.messager.alert('提示信息','并未勾选任何一条记录','info');
    }else{
        if(selections[0].verifyStatus != 0){
            $.messager.alert('提示信息','选择的内容已经审核完成','info');
        }else{
            var ids = "";
            for(var i = 0; i < selections.length;i++){
                if(i == selections.length-1){
                   ids += selections[i].id;
                }else{
                    ids += selections[i].id + "_";
                }
            }
            var title = "审核";
            var url = $.util.getRootPath() + '/page/operatorManager/productVerify/verifyProduct.html?id='+ids;
            var dialog = $.easyui.showDialog({
                iconCls:"",
                title: title,
                width: 800,
                height: 460,
                maximizable: true,
                href: url,
                topMost: true,
                saveButtonText: '保存',
                onSave: function () {
                    verifyProductSubForm(dialog);
                }
            });
        }
    }
}

// 批量删除
function batchDelte(){
    var selections = $("#listTable").datagrid('getChecked');
    if(selections.length == 0){
        $.messager.alert('提示信息','并未勾选任何一条记录','info');
    }else{
        if(selections[0].verifyStatus == 0){
            $.messager.alert('提示信息','选择的商品为未审核状态，不能进行删除操作','info');
        }else{
            var verifyStr = "确定要删除选择的 <b>"+selections.length+"</b> 项内容吗?";
            $.messager.confirm('确认对话框', verifyStr, function(r){
                if (r){
                    var ids = "";
                    for(var i = 0; i < selections.length;i++){
                        if(i == selections.length-1){
                            ids += selections[i].id;
                        }else{
                            ids += selections[i].id + "_";
                        }
                    }
                    $.util.get($.util.getRequestJson('/json/productManager.productDelete.json'),{id:ids},function(data){
                        if(data.success){
                            $('#listTable').datagrid('reload');
                        }
                    });
                }
            });
        }
    }
}

// 推荐到首页
function batchRecommend(){
    var selections = $("#listTable").datagrid('getChecked');
    if(selections.length == 0){
        $.messager.alert('提示信息','并未勾选任何一条记录','info');
    }else{
        for(var i = 0; i < selections.length;i++){
            if(selections[i].verifyResult != 1){
                $.messager.alert('提示信息','选择的商品不是审核通过状态，不能进行推荐到首页操作','info');
                return;
            }
        }
        var verifyStr = "确定要将选择的 <b>"+selections.length+"</b> 项内容全部推荐到首页吗?";
        $.messager.confirm('确认对话框', verifyStr, function(r){
            if (r){
                var ids = "";
                for(var i = 0; i < selections.length;i++){
                    if(i == selections.length-1){
                        ids += selections[i].id;
                    }else{
                        ids += selections[i].id + "_";
                    }
                }
                $.util.get($.util.getRequestJson('/json/productManage.toHome.json'),{ids:ids},function(data){
                    if(data.success){
                        $('#listTable').datagrid('reload');
                        $('#listTable').datagrid('clearChecked');
                    }
                    $.easyui.messager.show(data.message);
                });
            }
        });

    }
}

// 查看商品详情
function findDetail(id){
    // TODO 传递要查看的商品id
    var title = "详情";
    var url = $.util.getRootPath() + '/page/productManage/productDetail.html?id='+id;
    var dialog = $.easyui.showDialog({
        iconCls:"",
        title: title,
        width: 800,
        height: 500,
        maximizable: true,
        href: url,
        topMost: true,
        enableSaveButton: false,
        closeButtonText: '关闭'
    });
}

// 审核商品
function verifyProduct(id){
    // TODO 传递需要审核的商品id
    var title = "商品审核";
    var url = $.util.getRootPath() + '/page/operatorManager/productVerify/verifyProduct.html';
    url = url + '?id=' + id;
    var dialog = $.easyui.showDialog({
        iconCls:"",
        title: title,
        width: 800,
        height: 500,
        maximizable: true,
        href: url,
        topMost: true,
        saveButtonText: '保存',
        onSave: function () {
            verifyProductSubForm(dialog);
        }
    });
}

// 审核商品操作方法
function verifyProductSubForm(dialog){
    var commtityType = parent.$("#commtityTypeVerify").combobox('getValues');
    var marketPrice = parent.$("#marketPrice").val();
    var needScore = parent.$("#needScore").val();
    var discountPrice = parent.$("#discountPrice").val();
    var discountScore = parent.$("#discountScore").val();
    var title = parent.$("#title").val();
    var id = parent.$("#id").val();
    var attachedFile = parent.$("#attachedFile").val();
    var attachedFileQuality = parent.$("#attachedFileQuality").val();
    var attributePrice = parent.$('#disPrice').attr('style');
    var attributeScore = parent.$('#disScore').attr('style');
    var attributeQuality = parent.$('#commQuality').attr('style');

    if(title.length>100){
        parent.$.messager.alert('商品名称过长');
        return;
    }
    if (commtityType == '请选择商品类别' || commtityType == "" || commtityType == null) {
        parent.$.messager.alert('请选择商品类别');
        return;
    }
    if(commtityType.length > 5){
        parent.$.messager.alert('最多可选5个分类');
        return;
    }
    if(!/^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(marketPrice) || marketPrice.length>18){
        parent.$.messager.alert('请正确输入商品价格');
        return;
    }
    if(!/^[0-9]*$/.test(needScore) || needScore.length>9){
        parent.$.messager.alert('请正确输入兑换积分');
        return;
    }
    if(!attributePrice){
        if(discountPrice == "" || discountPrice == null){
            parent.$.messager.alert('请输入优惠价格');
            return;
        }else{
            if(!/^(0|([1-9]\d*))(\.\d+)?$/.test(discountPrice) || discountPrice.length>18){
                parent.$.messager.alert('请正确输入优惠价格');
                return;
            }
        }
    }
    if(!attributeScore){
        if(discountScore == "" || discountScore == null){
            parent.$.messager.alert('请输入优惠兑换积分');
            return;
        }else{
            if(!/^[0-9]*$/.test(discountScore) || discountScore.length>9){
                parent.$.messager.alert('请正确输入优惠兑换积分');
                return;
            }
        }
    }
    if (attachedFile.length <= 0){
        parent.$.messager.alert('请至少上传一张商品图片');
        return;
    }
    if(!attributeQuality){
        if (attachedFileQuality.length <= 0){
            parent.$.messager.alert('请上传精品专区图片');
            return;
        }
    }

    var url = $.util.getRootPath() + '/productManage/checkProduct?dictionaryId='+commtityType;
    var form = parent.$('#verifyProduct').form('submit', {
        url: url,
        onSubmit: function () {
            return parent.$('#verifyProduct').form('validate');
        },
        success: function (data) {
            if (data.success) {
                $('#listTable').datagrid('reload');
                dialog.dialog('close');
            }
            $.easyui.messager.show(data.message);
        }
    });
}

// 删除商品
function deleteProduct(id){
    $.messager.confirm('确认对话框', '您确定要删除该商品吗？', function(r){
        if (r){
            var url = $.util.getRequestJson('/json/productManage.deleteProduct.json');
            $.util.get(url, {id:id}, function (res) {
                // 删除完成重新加载
                if (res.success) {
                    $('#listTable').datagrid('reload');
                }
                $.easyui.messager.show(res.message);
            });
        }
    });
}